<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="聊天日期" prop="time">
        <el-date-picker clearable v-model="queryParams.time" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择聊天日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="显示头像" prop="isAvatar">
        <el-input v-model="queryParams.isAvatar" placeholder="请输入显示头像" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="聊天标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入聊天标题" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="昵称a" prop="nickNameA">
        <el-input v-model="queryParams.nickNameA" placeholder="请输入昵称a" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="头像a" prop="avatarA">
        <el-input v-model="queryParams.avatarA" placeholder="请输入头像a" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="昵称b" prop="nickNameB">
        <el-input v-model="queryParams.nickNameB" placeholder="请输入昵称b" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="头像b" prop="avatarB">
        <el-input v-model="queryParams.avatarB" placeholder="请输入头像b" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="内容b" prop="contentB">
        <el-input v-model="queryParams.contentB" placeholder="请输入内容b" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="链接" prop="url">
        <el-input v-model="queryParams.url" placeholder="请输入链接" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="链接标题" prop="urlTitle">
        <el-input v-model="queryParams.urlTitle" placeholder="请输入链接标题" clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['system:config:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['system:config:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button class="copy-btn" type="success" plain icon="el-icon-qrcode" size="mini" :disabled="single"
                   v-hasPermi="['system:config:edit']"
                   @click="copyUrl"
        >复制链接
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-qrcode" size="mini" :disabled="single" @click="generateQR()">
          二维码
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['system:config:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['system:config:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id" width="50"/>
      <el-table-column label="聊天日期" align="center" prop="time" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示头像" align="center" prop="isAvatar">
        <template v-slot="scope">
          {{ scope.row.isAvatar === 1 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="聊天标题" align="center" prop="title"/>
      <el-table-column label="昵称a" align="center" prop="nickNameA"/>
      <el-table-column label="头像a" align="center" prop="avatarA">
        <template slot-scope="scope">
          <el-image v-if="scope.row.avatarA" :src="scope.row.avatarA" fit="contain" :lazy="true"
                    style="width: 50px; height: 50px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="昵称b" align="center" prop="nickNameB"/>
      <el-table-column label="头像b" align="center" prop="avatarB">
        <template slot-scope="scope">
          <el-image v-if="scope.row.avatarB" :src="scope.row.avatarB" fit="contain" :lazy="true"
                    style="width: 50px; height: 50px"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="内容a" align="center" prop="contentA" show-overflow-tooltip/>
      <el-table-column label="内容b" align="center" prop="contentB" show-overflow-tooltip/>
      <el-table-column label="更新时间" align="center" prop="updateTime"/>
      <el-table-column label="昵称" align="center" prop="updateBy"/>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 添加或修改聊天记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <div style="height: 500px;overflow-y: scroll;padding: 0 20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="聊天日期" prop="time">
            <el-date-picker style="width: 100%;" clearable v-model="form.time" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择聊天日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="显示头像" prop="isAvatar">
            <el-switch v-model="form.isAvatar" :active-value="1" :inactive-value="0"/>
          </el-form-item>
          <el-form-item label="聊天标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入聊天标题"/>
          </el-form-item>
          <el-form-item label="昵称a" prop="nickNameA">
            <el-input v-model="form.nickNameA" placeholder="请输入昵称a"/>
          </el-form-item>
          <el-form-item label="头像a" prop="avatarA">
            <el-input v-model="form.avatarA" placeholder="请输入头像a"/>
            <el-upload class="upload-demo" :multiple="false" accept="image/*" :limit="1" :action="uploadUrl"
                       :headers="uploadHeader" :file-list="fileListA" list-type="picture"
                       :on-success="uploadAvatarASuccess"
                       :on-remove="removeAvatarA"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="内容a" prop="contentA">
            <div style="display: flex;justify-content: space-between;gap: 10px;">
              <el-input v-model="checkString" placeholder="查找文本"/>
              <el-input v-model="replaceString" placeholder="替换文本"/>
              <el-button size="small" type="primary" @click="handleCheckString">查找</el-button>
              <el-button size="small" type="warning" @click="handleReplaceString">替换</el-button>
            </div>
            <el-input ref="textareaA" style="margin-top: 10px;" v-model="form.contentA" type="textarea" :rows="8"
                      placeholder="请输入内容A"
            />
          </el-form-item>
          <el-form-item label="昵称b" prop="nickNameB">
            <el-input v-model="form.nickNameB" placeholder="请输入昵称b"/>
          </el-form-item>
          <el-form-item label="头像b" prop="avatarB">
            <el-input v-model="form.avatarB" placeholder="请输入头像b"/>
            <el-upload class="upload-demo" :multiple="false" accept="image/*" :limit="1" :action="uploadUrl"
                       :headers="uploadHeader" :file-list="fileListB" list-type="picture"
                       :on-success="uploadAvatarBSuccess"
                       :on-remove="removeAvatarB"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="内容b" prop="contentB">
            <el-input v-model="form.contentB" placeholder="请输入内容b"/>
          </el-form-item>
          <el-form-item label="链接" prop="url">
            <el-input v-model="form.url" placeholder="请输入链接"/>
          </el-form-item>
          <el-form-item label="链接标题" prop="urlTitle">
            <el-input v-model="form.urlTitle" placeholder="请输入链接标题"/>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="链接二维码" :visible.sync="openQrcode" width="250px" destroy-on-close>
      <div style="text-align: center;">
        <el-image :src="qrcodeUrl" fit="contain" :lazy="true" style="width: 200px; height: 200px"></el-image>
      </div>
      <div slot="footer" style="text-align: center;">
        <el-button type="primary" @click="openQrcode = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, delConfig, addConfig, updateConfig, uploadAvatar } from '@/api/system/chatconfig'
import { getToken } from '@/utils/auth'
import VueQrcode from 'vue-qrcode'
import QRCode from 'qrcode'
import Clipboard from 'clipboard'

export default {
  name: 'Config',
  components: {
    VueQrcode
  },
  data() {
    return {
      recordUrl: '',
      qrcodeUrl: '',
      openQrcode: false,
      fileListA: [],
      fileListB: [],
      uploadHeader: {
        Authorization: 'Bearer ' + getToken()
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天记录表格数据
      configList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null,
        isAvatar: null,
        title: null,
        nickNameA: null,
        avatarA: null,
        nickNameB: null,
        avatarB: null,
        contentA: null,
        contentB: null,
        url: null,
        urlTitle: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      checkString: '',
      replaceString: '',
      uploadUrl: '',
      contentList: [],
      searchIndex: 0,
      row: {}
    }
  },
  created() {
    this.getList()
    this.uploadUrl = process.env.VUE_APP_BASE_API + '/common/upload'
  },
  methods: {
    async copyUrl() {
      try {
        const text = window.location.origin + '?id=' + this.row.uniqueId
        // 创建text area
        let textArea = document.createElement('textarea')
        textArea.value = text
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = 'absolute'
        textArea.style.opacity = 0
        textArea.style.left = '-999999px'
        textArea.style.top = '-999999px'
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? res() : rej()
          textArea.remove()
        }).then(res => {
          this.clipboardSuccess()
        })
      } catch (err) {
        console.error('Failed to copy: ', err)
      }
    },
    generateQR() {
      this.openQrcode = true
      // 发布上线时需要修改为实际前端部署的地址
      this.recordUrl = window.location.origin + '?id=' + this.row.uniqueId
      QRCode.toDataURL(this.recordUrl)
        .then(qrUrl => {
          this.qrcodeUrl = qrUrl
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleCheckString() {
      const textArea = this.$refs.textareaA.$el
      const searchText = this.checkString
      const caseSensitive = true // 如果需要大小写不敏感，可以设置为 false

      if (!searchText) {
        this.$message.warning('请输入要查找的文字！')
        return
      }

      let text = this.form.contentA
      let index = -1

      if (caseSensitive) {
        index = text.indexOf(searchText)
      } else {
        index = text.toLowerCase().indexOf(searchText.toLowerCase())
      }
      const resultList = this.contentList.filter((content) => {
        return !content.show && content.val === searchText
      })

      console.log(resultList)

      if (resultList.length !== 0) {
        // 选中找到的文字
        textArea.lastElementChild.focus()
        this.$nextTick(() => {
          const result = resultList[0]
          this.searchIndex = result.length
          textArea.lastElementChild.setSelectionRange(result.length, result.length + searchText.length)
          if (resultList.length === 1) {
            this.contentList.forEach((content) => {
              if (content.show && content.val === searchText) {
                content.show = false
              }
            })
          } else {
            result.show = true
          }
        })
      } else {
        this.$message.warning('未找到文字：' + searchText)
      }
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess('复制成功')
    },
    handleReplaceString() {
      const searchText = this.checkString
      const replaceText = this.replaceString
      const caseSensitive = true // 如果需要大小写不敏感，可以设置为 false

      if (!searchText || !replaceText) {
        this.$message.warning('请确保已输入要查找和替换的文字！')
        return
      }

      let text = this.form.contentA

      if (caseSensitive) {
        const start = text.substring(0, this.searchIndex)
        const end = text.substring(this.searchIndex + searchText.length)
        text = start + replaceText + end
      } else {
        const regExp = new RegExp(searchText, 'gi') // g: 全局匹配, i: 忽略大小写
        text = text.replace(regExp, replaceText)
      }

      this.form.contentA = text
      this.contentList = this.refreshContent(text)
      this.$message.success('替换成功')
    },
    uploadAvatarASuccess(response) {
      this.form.avatarA = response.url
    },
    uploadAvatarBSuccess(response) {
      this.form.avatarB = response.url
    },
    removeAvatarA() {
      this.form.avatarA = ''
    },
    removeAvatarB() {
      this.form.avatarB = ''
    },
    /** 查询聊天记录列表 */
    getList() {
      this.loading = true
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.fileListA = []
      this.fileListB = []
      this.checkString = ''
      this.replaceString = ''
      this.form = {
        id: null,
        time: null,
        isAvatar: null,
        title: null,
        nickNameA: null,
        avatarA: null,
        nickNameB: null,
        avatarB: null,
        contentA: null,
        contentB: null,
        url: null,
        urlTitle: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      if (selection.length === 1) {
        this.row = selection[0]
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加聊天记录'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getConfig(id).then(response => {
        this.form = response.data
        this.contentList = this.refreshContent(this.form.contentA)
        this.fileListA = [{ url: response.data.avatarA }]
        this.fileListB = [{ url: response.data.avatarB }]
        this.open = true
        this.title = '修改聊天记录'
      })
    },
    refreshContent(detail) {
      const strList = []
      const constList = detail.split('\n')
      let totalLength = 0
      let last = 0
      constList.forEach((list, i) => {
        const items = list.split('-')
        if (items && items.length > 0) {
          let index = 1
          items.forEach((item, j) => {
            totalLength += last + (j > 0 ? 1 : 0) + (i > 0 ? index : 0)
            strList.push({
              val: item,
              length: totalLength,
              show: false
            })
            last = item.length
            if (index > 0) {
              index--
            }
          })
        }
      })
      console.log(strList)
      return strList
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addConfig(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除聊天记录编号为"' + ids + '"的数据项？').then(function() {
        return delConfig(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
